import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;


public class FileTreeParser {

	/**
	 * @Author: Lucky
	 * Program to parse the directory structure for method name extraction 
	 */
	
	public File rootDir=new File("/home/sangeeta/2Research/jboss_trunk/");
	public String database="jboss";
	public String user="root";
	public String password="123";
	
	public int count=0;
	ArrayList<String> flist=new ArrayList<String>();
	
	public Connection conn=null;
	
	public void parseDirectory(File dir)
	{
		System.out.println("Inside Directory:"+dir+"==========================");
		File list[]=dir.listFiles();
		System.out.println("Length:"+list.length);
		for (int i=0; i<list.length;i++)
		{
			if(list[i].getName().startsWith(".")) // Skip system folders eg. .data .config etc
				continue;
			System.out.println(list[i]);
			if(list[i].isDirectory())
				parseDirectory(list[i]);
			else if (list[i].isFile() && list[i].getName().endsWith(".java"))
			{
				count++;
				if(!flist.contains(list[i].getName()))
					flist.add(list[i].getName());
				parseFile(list[i]);
			}
		}			
	}
	
	public void parseFile(File file)
	{
		System.out.println("Inside parseFile()");
		String query="Select * from fname_fdir where fname='"+file.getName()+"'";
		try {
			Statement stmt=conn.createStatement();
			stmt.execute(query);
			ResultSet res=stmt.getResultSet();
			ArrayList<fid_fdir> dirList=new ArrayList<fid_fdir>();
			while(res.next())
			{
				dirList.add(new fid_fdir(res.getString("fid"),res.getString("fdir")));
			}
			
			int match_length[]=new int[dirList.size()];
			for(int i=0;i<dirList.size();i++)
			{
				String fdir=dirList.get(i).fdir;
				String filedir=file.getParentFile().getPath();
				boolean match=true;
				
				while(match)
				{
				if(fdir.contains(filedir))
					break;
				int pos=filedir.indexOf("/");
				if(pos == -1)
					break;
				filedir=filedir.substring(pos+1);
				System.out.println("Filedir:"+filedir);
				}
				match_length[i]=filedir.split("/").length;
			}
			int index=-1,max=0;
			for (int j=0 ; j<match_length.length;j++)
			{
				if(match_length[j] > max)
				{
					index=j;
					max=match_length[j];
				}
				
			}
			if(index != -1)
				findMethodList(dirList.get(index).fid,file);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void findMethodList(String fid,File file)
	{
		 StringBuffer contents = new StringBuffer();
		 try {
			 BufferedReader input =  new BufferedReader(new FileReader(file));
			 try {
				 String line = null;
				 while (( line = input.readLine()) != null)
				 {
		          contents.append(line);
		          contents.append(System.getProperty("line.separator"));
				 }
			 }
			 finally {
				 input.close();
			 }
		 }
		 catch (IOException ex){
			 ex.printStackTrace();
		 }
		 
		 String content=contents.toString();
		 //System.out.println("Content is#################"+content);
		 //Check for public
		 String methodlist="";
		 while(true)
		 {
			 int beginindex=content.indexOf("public");
			 if (beginindex == -1)
				 break;
			 int endindex=content.indexOf("{", beginindex);
			 if (endindex == -1)
				 break;
			 String method=content.substring(beginindex, endindex);
			 if(method.indexOf(";") == -1 && method.indexOf("(") != -1)
			 {
				 method=method.substring(0, method.indexOf("("));
				 method=method.substring(method.lastIndexOf(" "));
				 System.out.println("Found Method:"+method);
				 methodlist=methodlist+","+method;
				 
			 }
			 content=content.substring(endindex);
		 }
		 updateFileTable(fid,methodlist); 
	}
	
	public void updateFileTable(String fid,String method)
	{
		String query="Select * from file_list_copy where fid='"+fid+"'";
		Statement stmt;
		String tokenlist="";
		try {
			stmt = conn.createStatement();
			stmt.execute(query);
			ResultSet res=stmt.getResultSet();
			while(res.next())
				tokenlist=res.getString("tokenlist");
			
			tokenlist=tokenlist+","+method;
			
			query="Update file_list_copy set tokenlist='"+tokenlist+"' where fid='"+fid+"'";
			stmt.executeUpdate(query);
			
			res.close();
			stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		FileTreeParser ftp=new FileTreeParser();
		ftp.conn=new db_conn().connect(ftp.database, ftp.user, ftp.password);
		
		try
		{
			ftp.parseDirectory(ftp.rootDir);
			
			System.out.println("Count="+ftp.count+"\nArray Length="+ftp.flist.size());
			if(ftp.conn!=null)
				ftp.conn.close();
		}
		catch (SQLException e) {
				e.printStackTrace();
		}
	}

}
